<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

function absint( $maybeint ) {
	return abs( intval( $maybeint ) );
}

function wp_unslash( $value ) {
	return stripslashes_deep( $value );
}

function stripslashes_deep($value) {
	if ( is_array($value) ) {
		$value = array_map('stripslashes_deep', $value);
	} elseif ( is_object($value) ) {
		$vars = get_object_vars( $value );
		foreach ($vars as $key=>$data) {
			$value->{$key} = stripslashes_deep( $data );
		}
	} elseif ( is_string( $value ) ) {
		$value = stripslashes($value);
	}

	return $value;
}

function sanitize_key( $key ) {
	$key = strtolower( $key );
	$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
	return $key;
}

function maybe_serialize( $data ) {
	if ( is_array( $data ) || is_object( $data ) )
		return serialize( $data );

	// Double serialization is required for backward compatibility.
	// See https://core.trac.wordpress.org/ticket/12930
	if ( is_serialized( $data, false ) )
		return serialize( $data );

	return $data;
}

function maybe_unserialize( $original ) {
	if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
		return @unserialize( $original );
	return $original;
}

function is_serialized( $data, $strict = true ) {
	// if it isn't a string, it isn't serialized.
	if ( ! is_string( $data ) ) {
		return false;
	}
	$data = trim( $data );
	if ( 'N;' == $data ) {
		return true;
	}
	if ( strlen( $data ) < 4 ) {
		return false;
	}
	if ( ':' !== $data[1] ) {
		return false;
	}
	if ( $strict ) {
		$lastc = substr( $data, -1 );
		if ( ';' !== $lastc && '}' !== $lastc ) {
			return false;
		}
	} else {
		$semicolon = strpos( $data, ';' );
		$brace     = strpos( $data, '}' );
		// Either ; or } must exist.
		if ( false === $semicolon && false === $brace )
			return false;
		// But neither must be in the first X characters.
		if ( false !== $semicolon && $semicolon < 3 )
			return false;
		if ( false !== $brace && $brace < 4 )
			return false;
	}
	$token = $data[0];
	switch ( $token ) {
		case 's' :
		if ( $strict ) {
			if ( '"' !== substr( $data, -2, 1 ) ) {
				return false;
			}
		} elseif ( false === strpos( $data, '"' ) ) {
			return false;
		}
		// or else fall through
		case 'a' :
		case 'O' :
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
		case 'b' :
		case 'i' :
		case 'd' :
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
	}
	return false;
}


function array_map_recursive($callback, $array) {
	foreach ($array as $key => $value) {
		if (is_array($array[$key])) {
			$array[$key] = array_map_recursive($callback, $array[$key]);
		}
		else {
			$array[$key] = call_user_func($callback, $array[$key]);
		}
	}
	return $array;
}

function the_excerpt($content = '', $length = 50){
	$length = abs((int)$length);
	if(strlen($content) > $length) {
		$content = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $content);
	}
	return $content;
}

function maybe_array($data) {
	return json_decode(json_encode($data), TRUE);
}

/**
 * array
 * 		[0] => array
 * 			['meta_key'] => post_related_content
 * 			['meta_value'] => array(0,1,2)
 * 		[1] => array
 * 			['meta_key'] => post_most_read
 * 			['meta_value'] => array(0,5)
 * 	*************************************
 * 	array
 * 		['post_related_content']
 * 	
 */

function format_meta_key($data, $key = '') {
	$data = maybe_array($data);
	if($data)
	{
		$reduced = array_reduce(
		$data, 
		function(&$result, $item) {
			$result[$item['meta_key']] = $item['meta_value'];
			return $result;
		},
		array()
	);
	return $reduced;
	}
	return array();
}

function iif($expression, $returntrue, $returnfalse = '')
{
	return ($expression ? $returntrue : $returnfalse);
}

function convertViToEn($str) {
    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
    $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
    $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
    $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
    $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
    $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
    $str = preg_replace("/(đ)/", 'd', $str);
    $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
    $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
    $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
    $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
    $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
    $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
    $str = preg_replace("/(Đ)/", 'D', $str);
    //$str = preg_replace('/(\s+)/i', '', $str);
    
    //$str = str_replace(" ", "-", str_replace("&*#39;","",$str));
    return $str;
}

function convertToURL($str) {
    $str = convertViToEn($str);
    $str = preg_replace('/[^A-Za-z0-9\ \_\-\.\/]/', '', $str);
    $str = preg_replace('/[[:space:]]+/', '-', $str);
    return $str;
}

function create_slug($title = "") {
	return strtolower(convertToURL($title));
}

function checkExpanded($menus, $result = array(), $selected = array(), $menu_tree = array()) {
	foreach($menus as $menu) {
		if (!empty($menu->child)) {
			foreach ($menu->child as $item) {
				if(in_array($item->term_id, $selected))
					$result[] = $menu->term_id;
			}
			$result = array_merge($result, checkExpanded($menu->child, $result,$selected, $menu_tree));
		}
	}
	return $result;
}

function print_menu($menu, $name = 'terms', &$selected = array(), &$checkExpanded = array()) {
	// if(!$selected)
		// global $selected;
	// if(!$checkExpanded)
		// global $checkExpanded;

	$strSelected = (isset($menu->term_id) && in_array($menu->term_id, $selected))?"checked='true'":"";
	$expanded = '';//(in_array($menu->term_id, $checkExpanded))?"class='collapsed'":"";
	$list_id = "menu_".$menu->term_id.$name;
	echo "<li $expanded><input type='checkbox' id='{$list_id}' name='$name' value='{$menu->term_id}' $strSelected><span><label for='{$list_id}'>{$menu->term_name}</label></span>";
	if (!empty($menu->child)) {
		echo '<ul>';
		foreach ($menu->child as $item) print_menu($item, $name, $selected, $checkExpanded);
		echo '</ul>';
	}
	echo '</li>';
}
function print_menu_select($menu, $selected = 0, $index = 0) {
	$hyphen = '';
	for($i = 0; $i < $index; $i++)
		$hyphen .= '- ';
	$attr = '';
	if($menu->term_id == $selected)
		$attr = 'selected';
	echo '<option value="'.$menu->term_id.'" '.$attr.'>' . $hyphen . $menu->term_name.'</option>';

	if (!empty($menu->child)) {
		$index++;
		foreach ($menu->child as $item) print_menu_select($item,$selected, $index);
	}
}
function html_encode($content)
{
	$content = trim($content);
	$content = htmlspecialchars_decode(html_entity_decode($content, ENT_QUOTES, 'UTF-8'), ENT_QUOTES);
	 return htmlspecialchars($content, ENT_QUOTES);
}

function html_decode($content)
{
	return htmlspecialchars_decode($content);
}

function getYoutube($id, $type = 'video/mp4', $quality = 'hd720') {
	parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id),$info); 
	$streams = explode(',',$info['url_encoded_fmt_stream_map']);

	parse_str(@$streams[0],$real_stream);;
	return @$real_stream['url'].'&signature='.@$real_stream['sig'];
}
